package com.example.myapplication.message;

import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.Toast;

import com.example.myapplication.R;

import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
    private Context context;
    private List<String> list;
    private View inflater;
    //构造方法，传入数据
    public MessageAdapter(Context context, List<String> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //创建ViewHolder，返回每一项的布局
        inflater = LayoutInflater.from(context).inflate(R.layout.item_list,parent,false);
        MessageViewHolder myViewHolder = new MessageViewHolder(inflater);
        myViewHolder.demoView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                int position = myViewHolder.getAdapterPosition();
                String test = list.get(position);
                Toast.makeText(v.getContext(),"you clicked " + test,Toast.LENGTH_SHORT).show();
            }
        });
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MessageViewHolder holder, int position) {
        //将数据和控件绑定
        holder.textView.setText(list.get(position));
    }
    @Override
    public int getItemCount() {
        //返回Item总条数
        return list.size();
    }
    //内部类，绑定控件
    class MessageViewHolder extends RecyclerView.ViewHolder{
        View demoView;
        TextView textView;
        public MessageViewHolder(View itemView) {
            super(itemView);
            demoView = itemView;
            textView = (TextView) itemView.findViewById(R.id.text_view);
        }
    }
}

